/*
	fmtunePlugin.cpp

	Copyright (c) 2009 by Lms <lms.cze7@gmail.com>

 ***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************
*/

#include "fmtunePlugin.h"

TreeModelItem cntfmtune;
PluginSystemInterface *fmtunePS;

bool fmtunePlugin::init(PluginSystemInterface *plugin_system)
{
	qRegisterMetaType<TreeModelItem>("TreeModelItem");

	PluginInterface::init(plugin_system);
	fmtunePluginIcon = new QIcon(":/icons/fmtune.png");
	fmtunePluginSystem = plugin_system;

	fmtunePS = fmtunePluginSystem;

	m_event_init =  fmtunePluginSystem->registerEventHandler("Core/Layers/Initialized", this);
	m_event_context =  fmtunePluginSystem->registerEventHandler("Core/ContactList/ContactContext", this);
	m_event_tooltip = fmtunePluginSystem->registerEventHandler("Core/ContactList/AskTooltip", this);
	m_event_additional_info = fmtunePluginSystem->registerEventHandler("Core/ContactList/AskItemAdditionalInfo", this);
	//m_event_receivelevel3 = fmtunePluginSystem->registerEventHandler("Core/ChatWindow/ReceiveLevel3", this);

	return true;
}

void fmtunePlugin::release()
{
}

void fmtunePlugin::processEvent(Event &event)
{
	if (event.id == m_event_init)
		load();
	else if (event.id == m_event_context)
	{
		eventItem = *(TreeModelItem *)(event.args.at(0));
		if (eventItem.m_protocol_name == "FMtune" /*&& eventItem.m_item_type == 0*/)
		{
			createContextMenu();
			loadStations();
			m_item_menu->popup(QCursor::pos());
		}
	}
	else if (event.id == m_event_receivelevel3)
	{
		TreeModelItem item = *(TreeModelItem *)(event.args.at(0));
		QString *msg = (QString *)(event.args.at(1));
		if (item.m_protocol_name == "FMtune")
		{
			msg->replace("&lt;", "<");
			msg->replace("&gt;", ">");
		}
	}
	else if (event.id == m_event_tooltip)
	{
		TreeModelItem item = *(TreeModelItem *)(event.args.at(0));
		QString *tooltip = (QString *)(event.args.at(1));
		if (item.m_protocol_name == "FMtune")
		{
			QString infoTitle, infoURL, infoBitrate, infoDescription;
#ifdef useBASS
			infoTitle = BASSGetInfoRadio();
			infoURL = BASSGetInfoURL();
			infoBitrate = BASSGetInfoBitrate();
			infoDescription = BASSGetInfoSong();
#else
			infoTitle = phononStream->metaData().value("TITLE");
			infoURL = phononStream->currentSource().url().toString();
			infoBitrate = phononStream->metaData().value("BITRATE");
			infoDescription = phononStream->metaData().value("DESCRIPTION");
#endif

			QString text;
			text = tr("<b>FMtune</b><br/>\nTitle: %title% <br/>\nURL: %url% <br/>\nBitrate: %bitrate% <br/>\nDescription: %description%");

			text.replace(QString("%title%"), infoTitle, Qt::CaseInsensitive);
			text.replace(QString("%url%"), infoURL, Qt::CaseInsensitive);
			text.replace(QString("%bitrate%"), infoBitrate, Qt::CaseInsensitive);
			text.replace(QString("%description%"), infoDescription, Qt::CaseInsensitive);

			*tooltip = text;
		}
	}
	else if (event.id == m_event_additional_info)
	{
		TreeModelItem item = *(TreeModelItem *)(event.args.at(0));
		QStringList *info = (QStringList *)(event.args.at(1));
		if (item.m_protocol_name == "FMtune")
		{
			if (item.m_item_name == "fmtune")
				*info << "You";
			else
			{
				qDebug() << "haha";
			}
		}
	}
}

QWidget *fmtunePlugin::settingsWidget()
{
	m_settings_widget = new fmtuneSettings(m_profile_name);
	return m_settings_widget;
}

QString fmtunePlugin::name()
{
	return "FMtune";
}

QString fmtunePlugin::description()
{
	return "FMtune plugin";
}

QIcon *fmtunePlugin::icon()
{
	return fmtunePluginIcon;
}

QString fmtunePlugin::type()
{
	return "other";
}

void fmtunePlugin::setProfileName(const QString &profileName)
{
	m_profile_name = profileName;
}

void fmtunePlugin::removeSettingsWidget()
{
	delete settingsWidget();
}

void fmtunePlugin::saveSettings()
{
	m_settings_widget->saveSettings();
}


void fmtunePlugin::load()
{
	QList<QVariant> list;

	TreeModelItem contact;
	contact.m_protocol_name = "FMtune";
	contact.m_account_name = "fmtune";
	contact.m_item_name = "accountFMtunePlugin";
	contact.m_item_type = 2;
	emit fmtunePluginSystem->addItemToContactList(contact, "FMtune");
	emit fmtunePluginSystem->setAccountIsOnline(contact, true);

	contact.m_item_name = "groupFMtunePlugin";
	contact.m_parent_name = "accountFMtunePlugin";
	contact.m_item_type = 1;
	emit fmtunePluginSystem->addItemToContactList(contact, "FMtune");

	contact.m_protocol_name = "FMtune";
	contact.m_account_name = "fmtune";
	contact.m_parent_name = "groupFMtunePlugin";
	contact.m_item_type = 0;

	contact.m_item_name = "FMtune";
	emit fmtunePluginSystem->addItemToContactList(contact, "FMtune");
	emit fmtunePluginSystem->setContactItemStatus(contact, *fmtunePluginIcon, "", 0);

/*
	emit fmtunePluginSystem->addMessageFromContact(contact, "text", QDateTime::currentDateTime());
	emit fmtunePluginSystem->setStatusMessage(contact, "text", QDateTime::currentDateTime());
	emit fmtunePluginSystem->setContactItemRow(contact, list, 1);
*/
////	QList<QVariant> list;
	//list.append("     " & "fefefefee");
	list.append("     --- --- ---");
	//list.append("     fefefefee2");

	emit fmtunePluginSystem->setContactItemRow(contact, list, 1);

	cntfmtune = contact;

//	emit fmtunePluginSystem->setContactItemRow(contact, list, 2);

#ifdef useBASS
	LoadBASS();
#else
	qDebug() << "[FMtune] Phonon version: " << Phonon::phononVersion();
	phononStream = new Phonon::MediaObject(this);
	phononOutput = new Phonon::AudioOutput(Phonon::MusicCategory);
	Phonon::Path path = Phonon::createPath(phononStream, phononOutput);
	Q_ASSERT(path.isValid());
#endif

	QString dbpath =SystemsCity::PluginSystem()->getProfilePath();
	if(dbpath.endsWith(QDir::separator())) dbpath.chop(1);
	dbpath += QDir::separator();
	dbpath += "fmtune.db";


	qDebug()<<"[FMtune]"<<"connecting to sqlite database";

	if (!sqldb.connect(dbpath, "FMtune")) {
		qDebug()<<"[FMtune]"<<"sqlite connect error"<<sqldb.db.lastError().text();
	}

	qDebug()<<"[FMtune]"<<"checking tables";

	QStringList slist;
	slist.clear();
	slist	<<"[id] INTEGER PRIMARY KEY AUTOINCREMENT"
			<<"[group] TEXT NOT NULL default ''"
			<<"[name] TEXT NOT NULL default ''"
			<<"[genre] TEXT NOT NULL default ''"
			<<"[language] TEXT NOT NULL default ''"
			<<"[image] TEXT NOT NULL default ''"
			<<"[url] TEXT NOT NULL default ''"
			<<"[defaultstream] INTEGER NOT NULL default '0'"
			;
	if (!sqldb.CreateTable("Stations", slist)) {
		qDebug()<<"[FMtune]"<<"error with create sqlite table Stations";
	}

	slist.clear();
	slist	<<"[id] INTEGER PRIMARY KEY AUTOINCREMENT"
			<<"[stationid] INTEGER NOT NULL default '0'"
			<<"[format] TEXT NOT NULL default ''"
			<<"[url] TEXT NOT NULL default ''"
			;
	if (!sqldb.CreateTable("Streams", slist)) {
		qDebug()<<"[FMtune]"<<"error with create sqlite table Streams";
	}

	qDebug()<<"[FMtune]"<<"tables checked";

/*
	QString sql;
	QSqlQuery query(sqldb.db);

	// Frekvence 1
	sql = "INSERT INTO Stations ([group], [name], [genre], [language], [url], [image], [defaultstream]) VALUES ('play.cz', 'Frekvence 1', '', '', 'http://www.play.cz/images/radia/player/frekvence-1.png', 'www.frekvence1.cz', '1')";
	query.exec(sql);

	sql = "INSERT INTO Streams ([stationid], [format], [url]) VALUES ('1', '128 kbps WMA', 'http://www.play.cz/radio/frekvence1-128.asx')";
	query.exec(sql);
	sql = "INSERT INTO Streams ([stationid], [format], [url]) VALUES ('1', '64 kbps WMA', 'http://www.play.cz/radio/frekvence1-64.asx')";
	query.exec(sql);
	sql = "INSERT INTO Streams ([stationid], [format], [url]) VALUES ('1', '32 kbps WMA', 'http://www.play.cz/radio/frekvence1-32.asx')";
	query.exec(sql);
	sql = "INSERT INTO Streams ([stationid], [format], [url]) VALUES ('1', '16 kbps WMA', 'http://www.play.cz/radio/frekvence1-16.asx')";
	query.exec(sql);
	sql = "INSERT INTO Streams ([stationid], [format], [url]) VALUES ('1', '32 kbps AAC+', 'http://www.play.cz/radio/frekvence1-32.aac.m3u')";
	query.exec(sql);


	// Jih
	sql = "INSERT INTO Stations ([group], [name], [genre], [language], [url], [image], [defaultstream]) VALUES ('play.cz', 'Jih', '', '', 'http://www.play.cz/images/radia/player/radio-jih.png', 'www.radiojih.cz', '1')";
	query.exec(sql);

	sql = "INSERT INTO Streams ([stationid], [format], [url]) VALUES ('2', '128 kbps WMA', 'http://www.play.cz/radio/jih128.asx')";
	query.exec(sql);
	sql = "INSERT INTO Streams ([stationid], [format], [url]) VALUES ('2', '64 kbps WMA', 'http://www.play.cz/radio/jih64.asx')";
	query.exec(sql);
	sql = "INSERT INTO Streams ([stationid], [format], [url]) VALUES ('2', '32 kbps WMA', 'http://www.play.cz/radio/jih32.asx')";
	query.exec(sql);


	// Impuls
	sql = "INSERT INTO Stations ([group], [name], [genre], [language], [url], [image], [defaultstream]) VALUES ('play.cz', 'Impuls', '', '', 'http://www.play.cz/images/radia/player/radio-impuls.png', 'www.radioimpuls.cz', '1')";
	query.exec(sql);

	sql = "INSERT INTO Streams ([stationid], [format], [url]) VALUES ('3', '128 kbps WMA', 'http://www.play.cz/radio/impuls128.asx')";
	query.exec(sql);
	sql = "INSERT INTO Streams ([stationid], [format], [url]) VALUES ('3', '64 kbps WMA', 'http://www.play.cz/radio/impuls64.asx')";
	query.exec(sql);
	sql = "INSERT INTO Streams ([stationid], [format], [url]) VALUES ('3', '32 kbps WMA', 'http://www.play.cz/radio/impuls32.asx')";
	query.exec(sql);
	sql = "INSERT INTO Streams ([stationid], [format], [url]) VALUES ('3', '32 kbps AAC+', 'http://www.play.cz/radio/impuls32.aac.m3u')";
	query.exec(sql);
*/

	m_info = new Info();
	//m_info->setWindowFlags(Qt::Tool);

	m_equalizer = new Equalizer();
	//m_equalizer->setWindowFlags(Qt::Tool);

	m_recording = new Recording();
	//m_recording->setWindowFlags(Qt::Tool);

	m_editstations = new EditStations();

	m_fastaddstation = new FastAddStation();


	createContextMenu();

	loadStations();
	actionStations_Changed();
	actionStreams_Changed();

	QSettings settings(QSettings::defaultFormat(),QSettings::SystemScope, SystemsCity::PluginSystem()->getProfilePath(), "fmtune");
	if (settings.value("shortcuts/enabled", "0").toInt()==1){
		qDebug()<<"[FMtune]"<<"shortcuts enabled";
		GlobalShortcutManager::clear();
		GlobalShortcutManager::connect( QKeySequence(Qt::CTRL+Qt::ALT+Qt::Key_F), this, SLOT( actionShortcutRadioOnOff() ) );
//		GlobalShortcutManager::connect( QKeySequence(Qt::CTRL+Qt::ALT+Qt::Key_.), this, SLOT( actionShortcutVolumeUp() ) );
//		GlobalShortcutManager::connect( QKeySequence(Qt::CTRL+Qt::ALT+Qt::Key_,), this, SLOT( actionShortcutVolumeDown() ) );
//		GlobalShortcutManager::connect( QKeySequence(Qt::CTRL+Qt::ALT+Qt::Key_X), this, SLOT( actionShortcutVolumeMute() ) );
//		GlobalShortcutManager::connect( QKeySequence(Qt::CTRL+Qt::ALT+Qt::Key_L), this, SLOT(  ) );
//		GlobalShortcutManager::connect( QKeySequence(Qt::CTRL+Qt::ALT+Qt::Key_K), this, SLOT(  ) );
//		GlobalShortcutManager::connect( QKeySequence(Qt::CTRL+Qt::ALT+Qt::Key_S), this, SLOT(  ) );
	}

	QTimer *refreshtimer = new QTimer(this);
	connect(refreshtimer, SIGNAL(timeout()), this, SLOT(refreshtimerTimeout()));
	refreshtimer->setInterval(5000);
	refreshtimer->start(1000);
}

void fmtunePlugin::createContextMenu()
{
	QAction *menu_action_On = new QAction(QIcon(":/icons/play.png"), tr("Radio on"), this);
	connect(menu_action_On, SIGNAL(triggered()), this,  SLOT(actionRadioOnOff()));

	QAction *menu_action_Off = new QAction(QIcon(":/icons/stop.png"), tr("Radio off"), this);
	connect(menu_action_Off, SIGNAL(triggered()), this,  SLOT(actionRadioOnOff()));

	QAction *menu_action_CopySongName = new QAction(QIcon(":/icons/copy.png"), tr("Copy song name"), this);
	connect(menu_action_CopySongName, SIGNAL(triggered()), this,  SLOT(actionCopySongName()));

	QAction *menu_action_Info = new QAction(QIcon(":/icons/info.png"), tr("Information"), this);
	connect(menu_action_Info, SIGNAL(triggered()), this,  SLOT(actionInfo()));

	QAction *menu_action_Equalizer = new QAction(QIcon(":/icons/error.png"), tr("Equalizer"), this);
	connect(menu_action_Equalizer, SIGNAL(triggered()), this,  SLOT(actionEqualizer()));

	QAction *menu_action_Recording = new QAction(QIcon(":/icons/error.png"), tr("Recording"), this);
	connect(menu_action_Recording, SIGNAL(triggered()), this,  SLOT(actionRecording()));

	QAction *menu_action_EditStations = new QAction(QIcon(":/icons/editstations.png"), tr("Edit stations"), this);
	connect(menu_action_EditStations, SIGNAL(triggered()), this,  SLOT(actionEditStations()));

	QAction *menu_action_FastAddStation = new QAction(QIcon(":/icons/fastaddstation.png"), tr("Fast add station"), this);
	connect(menu_action_FastAddStation, SIGNAL(triggered()), this,  SLOT(actionFastAddStation()));


	m_item_menu_volume = new QMenu();
	m_item_menu_volume->clear();

	m_item_menu_volume->setTitle(tr("Volume"));
	m_item_menu_volume->setIcon(QIcon(":/icons/volume.png"));


	menu_volume_icon_unmute_label = new QLabel;
	menu_volume_icon_unmute_label->setAlignment(Qt::AlignCenter);
	menu_action_volume_icon_unmute = new QWidgetAction(this);
	menu_action_volume_icon_unmute->setDefaultWidget(menu_volume_icon_unmute_label);
	menu_volume_icon_unmute_label->setText(
		"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">"
		"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">"
		"p, li { white-space: pre-wrap; }"
		"</style></head><body>"
		"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><img src=\":/icons/volume_unmute.png\" /></p></body></html>"
		);
	m_item_menu_volume->addAction(menu_action_volume_icon_unmute);

	menu_volume_slider_slider = new QSlider;
	menu_volume_slider_slider->setMaximum(100);
	//menu_volume_slider_slider->setFixedWidth(20);
	menu_volume_slider_slider->setTickPosition(QSlider::TicksBothSides);

	menu_action_volume_slider = new QWidgetAction(this);
	menu_action_volume_slider->setDefaultWidget(menu_volume_slider_slider);
	m_item_menu_volume->addAction(menu_action_volume_slider);

	QSettings settings(QSettings::defaultFormat(),QSettings::SystemScope, SystemsCity::PluginSystem()->getProfilePath(), "fmtune");
	if (settings.value("volume/value", "50").toInt()==0) {	//slider need change
		menu_volume_slider_slider->setValue(1);
	}

	menu_volume_icon_mute_label = new QLabel;
	menu_volume_icon_mute_label->setAlignment(Qt::AlignCenter);
	menu_action_volume_icon_mute = new QWidgetAction(this);
	menu_action_volume_icon_mute->setDefaultWidget(menu_volume_icon_mute_label);
	menu_volume_icon_mute_label->setText(
		"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">"
		"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">"
		"p, li { white-space: pre-wrap; }"
		"</style></head><body>"
		"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><img src=\":/icons/volume_mute.png\" /></p></body></html>"
		);
	m_item_menu_volume->addAction(menu_action_volume_icon_mute);


	menu_volume_value_label = new QLabel;
	menu_volume_value_label->setAlignment(Qt::AlignCenter);
	menu_action_volume_value = new QWidgetAction(this);
	menu_action_volume_value->setDefaultWidget(menu_volume_value_label);
	menu_volume_value_label->setText(QString(tr("%1\%")).arg(100));
	m_item_menu_volume->addAction(menu_action_volume_value);

	menu_volume_mute_check = new QCheckBox;
	menu_volume_mute_check->setText(tr("Mute"));
	menu_action_volume_mute = new QWidgetAction(this);
	menu_action_volume_mute->setDefaultWidget(menu_volume_mute_check);
	m_item_menu_volume->addAction(menu_action_volume_mute);

	connect(menu_volume_slider_slider, SIGNAL(valueChanged(int)), this,  SLOT(actionVolumeChanged(int)));
	connect(menu_volume_mute_check, SIGNAL(stateChanged(int)), this,  SLOT(actionMuteChanged(int)));
	menu_volume_mute_check->setDisabled(true);

	menu_volume_slider_slider->setValue(settings.value("volume/value", "50").toInt());
	if (settings.value("volume/mute", "").toInt()==1) {
		menu_volume_mute_check->setCheckState(Qt::Checked);
	}
	else {
		menu_volume_mute_check->setCheckState(Qt::Unchecked);
	}

	menu_title_label = new QLabel;
	menu_title_label->setAlignment(Qt::AlignCenter);
	menu_action_title = new QWidgetAction(this);
	menu_action_title->setDefaultWidget(menu_title_label);
	menu_title_label->setText("<b>FMtune</b>");

	menu_stations_combo = new QComboBox;

	/*QStandardItemModel *model;
	model = new QStandardItemModel;

	menu_stations_combo = new TreeComboBox;
	menu_stations_combo->setModel(model);*/

	connect(menu_stations_combo, SIGNAL(currentIndexChanged(int)), this,  SLOT(actionStations_Changed()));
	menu_action_stations = new QWidgetAction(this);
	menu_action_stations->setDefaultWidget(menu_stations_combo);

	menu_streams_combo = new QComboBox;
	connect(menu_streams_combo, SIGNAL(currentIndexChanged(int)), this,  SLOT(actionStreams_Changed()));
	menu_action_streams = new QWidgetAction(this);
	menu_action_streams->setDefaultWidget(menu_streams_combo);

	m_item_menu = new QMenu();
	m_item_menu->clear();

	m_item_menu->addAction(menu_action_title);
#ifdef useBASS
	if (BASSIsPlaying()==false) {	// Play
#else
	if (phononStream->state()!=Phonon::PlayingState) {	// Play
#endif
		m_item_menu->addAction(menu_action_On);
	}
	else {	// Stop
		m_item_menu->addAction(menu_action_Off);
	}
	m_item_menu->addSeparator();
	m_item_menu->addAction(menu_action_stations);
	m_item_menu->addAction(menu_action_streams);
	m_item_menu->addSeparator();
	m_item_menu->addAction(menu_action_CopySongName);
//	m_item_menu->addSeparator();
//	m_item_menu->addAction(menu_action_Info);
//	m_item_menu->addAction(menu_action_Equalizer);
//	m_item_menu->addAction(menu_action_Recording);
	m_item_menu->addMenu(m_item_menu_volume);
	m_item_menu->addAction(menu_action_EditStations);
	m_item_menu->addAction(menu_action_FastAddStation);

	connect(m_item_menu, SIGNAL(aboutToShow()), this,  SLOT(actionaboutToShow()));
}

void fmtunePlugin::actionVolumeChanged(int val)
{
	qDebug() << "[FMtune]" << "actionVolumeChanged" << val;

	menu_volume_value_label->setText(QString(tr("%1\%")).arg(val));

	QSettings settings(QSettings::defaultFormat(),QSettings::SystemScope, SystemsCity::PluginSystem()->getProfilePath(), "fmtune");
	settings.setValue("volume/value", val );
#ifdef useBASS
	BASSSetVolume(val);
#else
	phononOutput->setVolume(val/100.);
#endif
}
void fmtunePlugin::actionMuteChanged(int val)
{
	qDebug() << "[FMtune]" << "actionMuteChanged" << val;

	QSettings settings(QSettings::defaultFormat(),QSettings::SystemScope, SystemsCity::PluginSystem()->getProfilePath(), "fmtune");
	if (val==2) {
		settings.setValue("volume/mute", "1" );
	}
	else {
		settings.setValue("volume/mute", "0" );
	}
}

void fmtunePlugin::loadStations()
{
	QSettings settings(QSettings::defaultFormat(),QSettings::SystemScope, SystemsCity::PluginSystem()->getProfilePath(), "fmtune");
	QString stationid=settings.value("main/stationid", "").toString();
	QString streamid=settings.value("main/stream", "").toString();

	menu_stations_combo->clear();

	/*QStandardItemModel *model = (QStandardItemModel *)menu_stations_combo->model();
	model->clear();*/

	//TreeComboBoxView *view = (TreeComboBoxView *)menu_stations_combo->view();
	//model->appendRow(new QStandardItem("stanice"));

	QString sql;
	sql = "SELECT [id], [name] FROM Stations";
	QSqlQuery query2(sql, sqldb.db);
	while (query2.next()) {
		menu_stations_combo->addItem(query2.value(1).toString(), QVariant(query2.value(0).toString()));

		/*QStandardItem *itm;
		itm = new QStandardItem();

		itm->setText(query2.value(1).toString());
		itm->setData(QVariant(query2.value(0).toString()), Qt::UserRole);
		//model->item(0)->appendRow(itm);*/

		if (stationid==query2.value(0).toString()) {
			menu_stations_combo->setCurrentIndex( menu_stations_combo->count()-1 );
		}
	}

	//TreeComboBoxView *view = (TreeComboBoxView *)menu_stations_combo->view();
	//view->expandAll();
	//menu_stations_combo->setCurrentIndex( 4 );
}

void fmtunePlugin::actionShortcutRadioOnOff()
{
	qDebug()<<"[FMtune]"<<"Shortcut"<<"actionShortcutRadioOnOff";
	actionRadioOnOff();
}

void fmtunePlugin::actionShortcutVolumeUp()
{
	qDebug()<<"[FMtune]"<<"Shortcut"<<"actionShortcutVolumeUp";

}

void fmtunePlugin::actionShortcutVolumeDown()
{
	qDebug()<<"[FMtune]"<<"Shortcut"<<"actionShortcutVolumeDown";

}

void fmtunePlugin::actionShortcutVolumeMute()
{
	qDebug()<<"[FMtune]"<<"Shortcut"<<"actionShortcutVolumeMute";

}

void fmtunePlugin::actionRadioOnOff()
{
#ifdef useBASS
	if (BASSIsPlaying()==false){	// Play
#else
	if (phononStream->state()!=Phonon::PlayingState){	// Play
#endif
		qDebug()<<"[FMtune]"<<"Play";
		QString streamurl;

		QString sql;
		sql = QString("SELECT [url] FROM Streams WHERE id='%1'").arg( menu_streams_combo->itemData(menu_streams_combo->currentIndex(), Qt::UserRole).toString() );
		QSqlQuery query(sql, sqldb.db);
		while (query.next()) {
			streamurl = query.value(0).toString();
		}
		qDebug() << streamurl;

		//	qDebug() << menu_stations_combo->currentIndex();
		//	qDebug() << "QVariant" << menu_stations_combo->itemData(menu_stations_combo->currentIndex(), Qt::UserRole);

		//	bt.start(/*QThread::LowPriority*/);
#ifdef useBASS
		BASSPlay(streamurl);
#else
		phononStream->setCurrentSource(Phonon::MediaSource(QUrl(streamurl)));
		phononStream->play();
#endif
		//emit fmtunePS->setContactItemStatus(cntfmtune, QIcon(":/icons/play.png"), "", 0);
		//emit fmtunePS->setContactItemIcon(cntfmtune, QIcon(":/icons/play.png"), 0);
	}
	else {	// Stop
		qDebug()<<"[FMtune]"<<"Stop";
#ifdef useBASS
		BASSStop();
#else
		phononStream->stop();
#endif
		//emit fmtunePS->setContactItemStatus(cntfmtune, QIcon(":/icons/stop.png"), "", 0);
		//emit fmtunePS->setContactItemIcon(cntfmtune, QIcon(":/icons/stop.png"), 0);
	}
}

void fmtunePlugin::actionInfo()
{
	m_info->show();
}

void fmtunePlugin::actionEqualizer()
{
	m_equalizer->show();
}

void fmtunePlugin::actionRecording()
{
	m_recording->show();
}

void fmtunePlugin::actionEditStations()
{	
	m_editstations->sqldb=sqldb;
	m_editstations->showEvent();
	m_editstations->show();
}

void fmtunePlugin::actionFastAddStation()
{
	m_fastaddstation->sqldb=sqldb;
	m_fastaddstation->showEvent();
	m_fastaddstation->show();
}

void fmtunePlugin::actionCopySongName()
{
	QClipboard *clipboard = QApplication::clipboard();
	QString originalText = clipboard->text();
#ifdef useBASS
	clipboard->setText( BASSGetInfoSong() );
#else
	clipboard->setText( phononStream->metaData().value("TITLE") );
#endif
}

void fmtunePlugin::actionaboutToShow()
{
//	Menu_VolumeAction->setText("abcdef");
//	Menu_VolumeAction->setEnabled(false);
//	Menu_VolumeAction->setChecked(true);
}

void fmtunePlugin::actionStations_Changed()
{
	qDebug() << "stations-changed" << menu_stations_combo->currentIndex()<<"/"<<menu_stations_combo->count() << menu_stations_combo->itemData(menu_stations_combo->currentIndex(), Qt::UserRole).toString();

	if (menu_stations_combo->currentIndex()!=-1) {
		//TreeComboBoxView *view = (TreeComboBoxView *)menu_stations_combo->view();
		//qDebug()<<	view->currentIndex() ;
		//view->expandAll();

		menu_streams_combo->clear();

		QString sql;
		sql = QString("SELECT [id], [format] FROM Streams WHERE stationid='%1'").arg( menu_stations_combo->itemData(menu_stations_combo->currentIndex(), Qt::UserRole).toString() );
		QSqlQuery query(sql, sqldb.db);
		while (query.next()) {
			menu_streams_combo->addItem(query.value(1).toString(), QVariant(query.value(0).toString()));
		}

		QSettings settings(QSettings::defaultFormat(),QSettings::SystemScope, SystemsCity::PluginSystem()->getProfilePath(), "fmtune");
		settings.setValue("main/stationid", menu_stations_combo->itemData(menu_stations_combo->currentIndex(), Qt::UserRole).toString() );
		//settings.setValue("main/streamid", menu_streams_combo->itemData(menu_streams_combo->currentIndex(), Qt::UserRole).toString() );
	}
}

void fmtunePlugin::actionStreams_Changed()
{
	qDebug() << "streams-changed" << menu_streams_combo->currentIndex() << menu_streams_combo->itemData(menu_streams_combo->currentIndex(), Qt::UserRole).toString();

	if (menu_streams_combo->currentIndex()!=-1) {
		QSettings settings(QSettings::defaultFormat(),QSettings::SystemScope, SystemsCity::PluginSystem()->getProfilePath(), "fmtune");
		settings.setValue("main/stationid", menu_stations_combo->itemData(menu_stations_combo->currentIndex(), Qt::UserRole).toString() );
		settings.setValue("main/streamid", menu_streams_combo->itemData(menu_streams_combo->currentIndex(), Qt::UserRole).toString() );

/*		//If radio playing - change station
#ifdef useBASS
		if (BASSIsPlaying()==true) {	// Play
			BASSStop();
			actionRadioOnOff();
		}
#else
		if (phononStream->state()==Phonon::PlayingState) {	// Play
			phononStream->stop();
			actionRadioOnOff();
		}
#endif
*/
	}
}

void fmtunePlugin::refreshtimerTimeout()
{
	QList<QVariant> list;
#ifdef useBASS
	if (BASSGetInfoSong()==""){
		list.append( "..." );
	}
	else {
		list.append( BASSGetInfoSong() );
	}
#else
	if (phononStream->metaData().value("TITLE")==""){
		list.append( "..." );
	}
	else {
		list.append( phononStream->metaData().value("TITLE") );
	}
#endif
	
	emit fmtunePS->setContactItemRow(cntfmtune, list, 1);

	//emit fmtunePS->addItemToContactList(cntfmtune, "FMtune - "+BASSGetInfoRadio());
	//emit fmtunePS->setContactItemRow(cntfmtune, list, 1);
}

Q_EXPORT_PLUGIN2(fmtunePlugin, fmtunePlugin);
